<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\1\6 0006
 * Time: 10:44
 */
namespace app\api\controller\v1;
use app\api\model\Version;
use app\common\lib\exception\ApiException;
use app\common\lib\redis\PhpRedis;
use think\Log;
class Index extends AuthBase {

    public $headers;

    /**
     * app检测更新
     * @author 王柯 <wangke.email@foxmail.com>
     * @return ApiException|array|string|\think\response\Json
     */
    public function check_update(){
        //获取header
        $this->headers = request()->header();

        //根据app_type查询更新
        $version = (new Version())
            ->check_update($this->headers['apptype']);

        if(empty($version)) {
            return new ApiException('error', 404);
        }

        if($version->version > $this->headers['version']) {
            $version->is_update = $version->is_force == 1 ? 2 : 1;
        }else {
            $version->is_update = 0;  // 0 不更新 ， 1需要更新, 2强制更新
        }

        //记录用户的基本信息
        $actives = [
            'version_code' => $this->headers['version'],
            'app_type' => $this->headers['apptype'],
            'did' => $this->headers['did'],
        ];

        try {
            model('AppActive')->save($actives);
        }catch (\Exception $e) {
            Log::write($e->getMessage());
        }

        return show(config('code.success'), 'OK', $version, 200);
    }

    /**
     * 记录app异常信息
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function write_app_exception(){
        //获取header
        $this->headers = request()->header();
        $data = $_POST;
        $data['app_type'] = $this->headers['apptype'];
        $data['did'] = $this->headers['did'];
        $data['version_code'] = $this->headers['version'];
        $data['create_time'] = time();

        try{
            model('AppException')
                ->allowField(true)
                ->save($data);
        }catch (\Exception $e){
            Log::write($e->getMessage());
        }
    }


}